<?php

namespace App\Listeners;

use App\Events\LeaveCar;
use App\Models\AbnormalCar;
use App\Models\BadCarLog;
use App\Models\ParkInfo;
use Illuminate\Contracts\Queue\ShouldQueue;
use DB;

/**
 * Class AddBadCarLogSubscriber
 * @package App\Listeners
 */
class  AddBadCarLogSubscriber implements ShouldQueue
{

    /**
     * @param $events
     */
    public function subscribe($events)
    {
        $events->listen(
            'App\Events\EnterCar',
            'App\Listeners\AddBadCarLogSubscriber@update'
        );

        $events->listen(
            'App\Events\LeaveCar',
            'App\Listeners\AddBadCarLogSubscriber@update'
        );
    }


    /**
     * @param LeaveCar $event
     * @return bool
     */
    public function update($event)
    {
        //是否不良车
        $vplCount = AbnormalCar::where('vpl_number', $event->data->vpl_number)->count();
        if ($vplCount  >= 1) {
            //更新记录

            $badCarLog = new BadCarLog();

            $badCar = $badCarLog->firstOrNew(
                [
                    'record_id' => $event->data->record_id,
                    'park_code' => $event->data->park_code
                ]
            );

            $event->data->charge_items = json_encode($event->data->charge_items);
            $saved = $badCar->fill((array) $event->data);

            $saved->save();
        }

        //是否不良车
        $vplCount = AbnormalCar::where('vpl_number', $event->data->vpl_number)->where("type",158)->count();
        if ($vplCount < 1) {
            return;
        }

        $parks = ParkInfo::where('park_code', $event->data->park_code)
            ->pluck('parking_name','park_code');
        $park_name = $parks[$event->data->park_code]??'';
        $message = "【布控车辆】灰名单，车牌号<".$event->data->vpl_number.">，已驶入<".$park_name.">停车场";

        $exist_data = DB::table("msgs")->where("park_code",$event->data->park_code)
            ->where("arm_code",$event->data->in_arm_code)
            ->where("message",$message)
            ->where("type",1)
            ->where("class",1)
            ->first();
        if(!empty($exist_data)) return;
        $re = [];
        $re['class'] = 1;
        $re['park_code'] = $event->data->park_code;
        $re['arm_code'] = $event->data->in_arm_code;
        $re['message'] = $message;
        $re['created_at'] = date("Y-m-d H:i:s");
        //存入数据库
        $report = DB::table('msgs')->insert($re);
        \Log::info("不良车记录");
    }
}
